package lv.ante.xwiki.filters;

import java.io.FilterWriter;
import java.io.IOException;
import java.io.Writer;

public class SkippingFilterWriter extends FilterWriter {
        private static final int EOF = -1;

        private char[] delimiterArr;

        private StringBuffer buffer = new StringBuffer();

        private int state = 0;

        private int count = 0;

        public SkippingFilterWriter(Writer output, String delimiter) {
                super(output);
                delimiterArr = delimiter.toCharArray();
        }

        public void write(int c) throws IOException {
//              System.err.println("c = " + (char)c + ", count = " +count + ", state = " + state);
                if (c == EOF) {
                        super.write(c);
                } else if (state == 2 * delimiterArr.length) {
                        // skip
                } else if (state < delimiterArr.length && delimiterArr[state] == c) {
                        state++;
                } else if (state >= delimiterArr.length
                                && state < 2 * delimiterArr.length
                                && delimiterArr[state - delimiterArr.length] == c) {
                        state++;
                        buffer.append(c);
                } else if (state < delimiterArr.length) {
                        state = 0;
                } else if (state > delimiterArr.length) {
                        state = delimiterArr.length;
                        super.write(buffer.toString());
                        buffer.delete(0, buffer.length());
                } else {
                        super.write(c);
                }
                count++;
        }

        public void write(char cbuf[], int off, int len) throws IOException {
                write(new String(cbuf), off, len);
        }

        public void write(String str, int off, int len) throws IOException {
                for (int i = off; i < len; i++) {
                        if (i < 0 || i >= str.length()) {
                                break;
                        }
                        write(str.charAt(i));
                }
        }
}
